package fr.imag.wifibot.master;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class Activator implements BundleActivator {

	private static BundleContext context;
	
	private static final boolean D = true;
	
	private static final int PORT = 6666;
	private ServerSocket serverSocket;
	private Socket socket;
	
	private Thread listeningThread;
	private boolean stopListening;
	
	private BufferedReader in;
	private PrintWriter out;

	static BundleContext getContext() {
		return context;
	}

	public void start(BundleContext bundleContext) throws Exception {
		Activator.context = bundleContext;
		
		if(D) System.out.println("The Master has arrived !");
		
		stopListening = false;
		
		final IMasterService service = new MasterService(out);
		
		context.registerService(IMasterService.class.getName(), service, null);
		System.out.println("IMasterService is registered");
		
		serverSocket = new ServerSocket(PORT);
		serverSocket.setSoTimeout(30000);
		
		listeningThread = new Thread(new Runnable() {
			public void run() {
				try {
					System.out.println("Waiting client...");
					while(!stopListening) {
						socket = serverSocket.accept();
						System.out.println("Client connected !");
						in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
						out = new PrintWriter(socket.getOutputStream());
						service.setOut(out);
						
						try{
							in.read();
						}
						catch (Exception e) {
							socket.close();
							out.close();
							in.close();
							service.setOut(null);
							System.out.println("Client disconnected !");
						}
					}
				}
				catch (Exception e) {}
			}
		});
		
		listeningThread.start();
	}

	public void stop(BundleContext bundleContext) throws Exception {
		Activator.context = null;

		try {
			stopListening = true;
			serverSocket.close();
			socket.close();
			out.close();
			in.close();
		}
		catch (Exception e) {}
		
		listeningThread.join();
		
		if(D) System.out.println("The Master is gone !");
	}
	
	public void sendMessage(String str) {
		if(out != null) {
			out.println(str);
			out.flush();
		}
		else
			System.out.println("Out null !");
	}

}
